package com.sy.simpleegg.mvp.model

import android.os.Environment
import com.google.gson.reflect.TypeToken
import com.sy.simpleegg.BuildConfig
import com.sy.simpleegg.R
import com.sy.simpleegg.app.App
import com.sy.simpleegg.base.BaseModel
import com.sy.simpleegg.bean.CashDataWhmhex
import com.sy.simpleegg.bean.CashGoodBean
import com.sy.simpleegg.bean.CheckMoneyBean
import com.sy.simpleegg.bean.CoinDataWhmhex
import com.sy.simpleegg.bean.OrderVerifyResult
import com.sy.simpleegg.bean.RepCashDataBean
import com.sy.simpleegg.bean.RepCashKkb
import com.sy.simpleegg.bean.RepCashLyysdk
import com.sy.simpleegg.bean.RepCashWhmhex
import com.sy.simpleegg.bean.RepCashYch
import com.sy.simpleegg.bean.RepCoinDataBean
import com.sy.simpleegg.bean.RepCoinKkb
import com.sy.simpleegg.bean.RepCoinWhmhex
import com.sy.simpleegg.bean.RepCoinYch
import com.sy.simpleegg.bean.SaveMoneyBean
import com.sy.simpleegg.bean.SupplementOrderBean
import com.sy.simpleegg.config.Config
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.constant.ControlBoard
import com.sy.simpleegg.constant.PackageType
import com.sy.simpleegg.constant.PayState
import com.sy.simpleegg.constant.PayType
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.http.HttpUtil
import com.sy.simpleegg.http.callback.UploadLogCallback
import com.sy.simpleegg.mvp.contract.MainContract
import com.sy.simpleegg.platform.BackstagePlatform
import com.sy.simpleegg.platform.kkb.bean.RecieveOrderKkbBean
import com.sy.simpleegg.platform.lyysdk.bean.RecieveOrderLyySdkBean
import com.sy.simpleegg.platform.whmhex.bean.RecieveOrderWhmMqttHexBean
import com.sy.simpleegg.platform.whmhex.bean.RecieveWithdrawalCoinOrderWhmMqttHexBean
import com.sy.simpleegg.platform.ychsdk.bean.RecieveOrderYchBean
import com.sy.simpleegg.room.CoinType
import com.sy.simpleegg.room.RoomUtil
import com.sy.simpleegg.room.entity.CashPackageEntity
import com.sy.simpleegg.room.entity.CoinEntity
import com.sy.simpleegg.room.entity.ControlBoardEntity
import com.sy.simpleegg.room.entity.OrderEntity
import com.sy.simpleegg.util.CommonUtil
import com.sy.simpleegg.util.DateTimeUtil
import com.sy.simpleegg.util.FileUtil
import com.sy.simpleegg.util.GsonUtil
import com.sy.simpleegg.util.Preference
import com.sy.simpleegg.util.SPHelper
import kotlinx.coroutines.delay
import okhttp3.Call
import okhttp3.Response
import java.io.File
import java.io.IOException

class MainModel: BaseModel(), MainContract.Model {

//    private var controller: SyController? = null

    /**
     * 接入第三方平台
     */
    private var p: BackstagePlatform by Preference(
        Constant.SETTING_OTHER_PLATFORM,
        BackstagePlatform.WHM_MQTT_HEX
    )

    /**
     * 国家地区
     */
    private var country: Int by Preference(Constant.SETTING_COUNTRY, Config.DEFAULT_COUNTRY_CODE)

    /**
     * 纸钞通道配置
     */
    private var channelParams: String by Preference(Constant.SETTING_CASH_CHANNEL_CONFIG, CommonUtil.getChannelMode(country))

    /**
     * 现金配置 lyy模板配置格式
     */
    private var cashConfigHex: String by Preference(Constant.SETTING_CASH_CONFIG, "0000000000000000000000000000000000000000")

    /**
     * 设备编号
     */
    private var devNumber: String by Preference(Constant.SETTING_DEVICE_NUMBER, "")

    /**
     * 记录进钞数据
     * index=0 1元纸钞数量
     * index=1 5元纸钞数量
     * index=2 10元纸钞数量
     * index=3 20元纸钞数量
     * index=4 50元纸钞数量
     * index=5 100元纸钞数量
     */
    private var markMoneyArr = longArrayOf(0, 0, 0, 0, 0, 0)

    private fun markMoneyClear() {
        markMoneyArr = longArrayOf(0, 0, 0, 0, 0, 0)
    }

    private var isUploading = false

    override fun initMqtt() {

    }

    override fun initDeviceSerialport() {
//        if (controller != null){
//            return
//        }
//        controller = SyController(
//            Constant.PORT_COIN,
//            SerialPort.BAUDRATE.B9600,
//            SerialPort.STOPB.B1,
//            SerialPort.DATAB.CS8,
//            SerialPort.PARITY.NONE,
//            false
//        )
    }

    override fun outChannel(channelNumber: Int) {
//        controller?.out(channelNumber)
    }

    override fun testChannel(channelNumber: Int) {
//        controller?.out(channelNumber)
    }

    override suspend fun clearCoins(k: String, coins: Long) {
        try {
            val lastCoins = RoomUtil.getLastCoin()
            if (lastCoins.isNullOrEmpty()){
                val coinEntity = CoinEntity().apply {
                    orderNumber = k
                    type = CoinType.CLEAR
                    this.coins = coins
                    date = DateTimeUtil.nowDate
                    time = DateTimeUtil.nowTime
                }
                RoomUtil.saveCoins(coinEntity)
            }else{
                val coin = lastCoins[0]
                if (coin.orderNumber != k){
                    val coinEntity = CoinEntity().apply {
                        orderNumber = k
                        type = CoinType.CLEAR
                        this.coins = coins
                        date = DateTimeUtil.nowDate
                        time = DateTimeUtil.nowTime
                    }
                    RoomUtil.saveCoins(coinEntity)
                }else{
                    val oldClear = coin.coins
                    val diff = coins - oldClear

                    coin.clearCoinTotal = coin.clearCoinTotal + diff
                    coin.outCoinTotal = coin.outCoinTotal + diff
                    coin.remainCoin = coin.remainCoin - diff
                    coin.coins = coins
                    coin.date = DateTimeUtil.nowDate
                    coin.time = DateTimeUtil.nowTime
                    RoomUtil.coinUpdate(coin)
                }
            }
            //更新订单表 出币数
            RoomUtil.updateOrderRealCoins(k, coins.toString())
        }catch (e: Exception){
            e.printStackTrace()
            logFile("保存清币数异常：${e.message}")
        }
    }

    override suspend fun checkReceiveMoney(tempMoney: Long, checkMoney: Long): CheckMoneyBean {
        return try {
            val res = CheckMoneyBean().apply { msg = "校验纸钞可出币数异常" }
            val tMoney = tempMoney * 100
            val cMoney = checkMoney * 100
            val canReceiveMoney = checkAllowDenomination(cMoney)
            logFile("校验纸钞面额结果:$canReceiveMoney")
            res.apply {
                res.result = canReceiveMoney
                msg = if (canReceiveMoney) "" else App.instance.getString(R.string.reject_denomination)
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("校验纸钞可出币数异常：${e.message}")
            CheckMoneyBean().apply { msg = "校验纸钞可出币数异常" }
        }
    }

    override suspend fun saveMoney(checkMoney: Long, totalMoney: Long): SaveMoneyBean? {
        return try {
            val cMoney = checkMoney * 100
            val tMoney = totalMoney * 100
            val coins = checkMoneyGetCoin(tMoney)
            if (coins == 0L){
                return null
            }
            markMoney(cMoney)
            val moneyArr = markMoneyArr
            SaveMoneyBean(cMoney.toString(), tMoney.toString(), coins.toString(), moneyArr)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("进钞数据处理异常：${e.message}")
            null
        }
    }

    override fun clearMarkMoney() {
        markMoneyClear()
    }

    override suspend fun initCashPackageData(platform: BackstagePlatform) {
        try {
            val count = RoomUtil.getCashPackageCount(platform)
            if (count == 0L){
                //创建默认数据
                val cashPackageEntity5 = CashPackageEntity().apply {
                    this.platform = platform
                    packageId = CommonUtil.getUuid()
                    price = "100"
                    coins = "1"
                    donate = "0"
                    sort = 5
                }
                val cashPackageEntity4 = CashPackageEntity().apply {
                    this.platform = platform
                    packageId = CommonUtil.getUuid()
                    price = "500"
                    coins = "5"
                    donate = "0"
                    sort = 4
                }
                val cashPackageEntity3 = CashPackageEntity().apply {
                    this.platform = platform
                    packageId = CommonUtil.getUuid()
                    price = "1000"
                    coins = "10"
                    donate = "0"
                    sort = 3
                }
                val cashPackageEntity2 = CashPackageEntity().apply {
                    this.platform = platform
                    packageId = CommonUtil.getUuid()
                    price = "2000"
                    coins = "20"
                    donate = "0"
                    sort = 2
                }
                val cashPackageEntity1 = CashPackageEntity().apply {
                    this.platform = platform
                    packageId = CommonUtil.getUuid()
                    price = "5000"
                    coins = "60"
                    donate = "0"
                    sort = 1
                }
                val cashPackageEntity0 = CashPackageEntity().apply {
                    this.platform = platform
                    packageId = CommonUtil.getUuid()
                    price = "10000"
                    coins = "140"
                    donate = "0"
                    sort = 0
                }

                RoomUtil.cashPackageInsert(mutableListOf(
                    cashPackageEntity0,
                    cashPackageEntity1,
                    cashPackageEntity2,
                    cashPackageEntity3,
                    cashPackageEntity4,
                    cashPackageEntity5
                    ))
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("初始化纸钞套餐数据处理异常：${e.message}")
        }
    }

    override suspend fun controlBoardConnectChange(controlBoard: ControlBoard, isConnect: Boolean) {
        try {
            val dateTime = DateTimeUtil.nowDateTime
            val controlBoardEntity = ControlBoardEntity().apply {
                type = controlBoard.type
                name = controlBoard.desc
                connect = if (isConnect) 1 else 0
                date = dateTime.substring(0, 10)
                time = dateTime.substring(11)
            }
            RoomUtil.insertControlBoard(controlBoardEntity)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("记录串口通讯设备连接状态异常：${e.message}")
        }
    }

    override suspend fun saveCashData(cash: Long, coins: Long): RepCashDataBean? {
        return try {
            //创建订单
            val order = OrderEntity().apply {
                uuid = ""
                amount = coins.toString()
                money = cash.toString()
                moneyList = "100,${cash/100};"
                platform = p
                goodType = PackageType.CASH
                isPay = PayState.COMPLETE
            }
            RoomUtil.orderInsert(order)
            val coin = CoinEntity().apply {
                orderNumber = ""
                type = CoinType.OUT
                this.coins = coins
                date = DateTimeUtil.nowDate
                time = DateTimeUtil.nowTime
            }
            RoomUtil.saveCoins(coin)
            createCashOrder(order.platform, order.uuid, order.money, order.amount, order.moneyList)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("记录串口通讯设备连接状态异常：${e.message}")
            null
        }
    }

    override suspend fun createClearOrder(orderNumber: String) {
        try {
            //创建订单
            val order = OrderEntity().apply {
                uuid = orderNumber
                this.orderNumber = orderNumber
                platform = p
                goodType = PackageType.NORMAL
                payType = PayType.CLEAR
                isPay = PayState.COMPLETE
            }
            RoomUtil.orderInsert(order)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("创建清币订单异常：${e.message}")
        }
    }

    override suspend fun getSaveCoinFinish(): MutableList<RepCoinDataBean>? {
        return try {
            RoomUtil.getSaveCoinCanReport()?.run {
                if (isEmpty()){
                    return null
                }

                val repList: MutableList<RepCoinDataBean> = mutableListOf()
                forEach { saveCoinEntity ->
                    val repData = when (p){
                        BackstagePlatform.DEF_MQTT -> null
                        BackstagePlatform.LYY_SDK -> null
                        BackstagePlatform.LYY_BOX -> null
                        BackstagePlatform.WHM_MQTT -> null
                        BackstagePlatform.WHM_MQTT_HEX -> {
                            RepCoinWhmhex(saveCoinEntity.uid, mutableListOf(CoinDataWhmhex(1, 1, saveCoinEntity.coins.toLong())))
                        }

                        BackstagePlatform.YCH_SDK -> {
                            RepCoinYch(saveCoinEntity.uid, saveCoinEntity.coins.toLong(), "", saveCoinEntity.sn)
                        }

                        BackstagePlatform.KKB -> {
                            RepCoinKkb(saveCoinEntity.uid, saveCoinEntity.coins.toLong(), "", saveCoinEntity.sn)
                        }
                    }

                    repList.add(RepCoinDataBean(p, saveCoinEntity.sn, repData))
                }
                repList
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("创建存币上报数据异常：${e.message}")
            mutableListOf()
        }
    }

    override suspend fun setSaveCoinComplete(orderNumber: String, step: Int) {
        try {
            RoomUtil.updateSaveCoinStep(orderNumber, step)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("更新存币订单步骤异常：${e.message}")
        }
    }

    override suspend fun saveWithdrawalCoinOrder(platform: BackstagePlatform, orderData: Any): Any? {
        return try {
            val orderEntity = when(platform){
                BackstagePlatform.DEF_MQTT -> null
                BackstagePlatform.LYY_SDK -> null
                BackstagePlatform.LYY_BOX -> null
                BackstagePlatform.WHM_MQTT_HEX -> {
                    val data = orderData as RecieveWithdrawalCoinOrderWhmMqttHexBean
                    val isExist = RoomUtil.verifyOrderNumber(platform, data.k) == 1
                    if (isExist){
                        logFile("whmhex存在相同的提币订单，不需要处理：${GsonUtil.getInstance()?.toJson(data)}")
                        null
                    }else {
                        OrderEntity().apply {
                            uuid = data.k
                            orderNumber = data.k
                            amount = data.coins
                            money = data.money
                            this.platform = platform
                            payType = PayType.WITHDRAWAL
                            info = data.walletType.toString()
                        }
                    }
                }
                else -> {
                    val data = orderData as RecieveOrderYchBean
                    OrderEntity().apply {
                        uuid = data.transId
                        orderNumber = data.transId
                        amount = data.coins
                        money = data.money
                        this.platform = platform
                        payType = PayType.WITHDRAWAL
                    }
                }
            }

            orderEntity?.let {
                RoomUtil.orderInsert(it)
                orderData
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("插入提币订单异常：${e.message}")
            null
        }
    }

    override suspend fun saveWriteOffOrder(platform: BackstagePlatform, orderData: Any): Any {
        return try {
            val orderEntity = when(platform){
                BackstagePlatform.DEF_MQTT -> null
                BackstagePlatform.LYY_SDK -> null
                BackstagePlatform.LYY_BOX -> null
                BackstagePlatform.WHM_MQTT_HEX -> {
                    null
                }
                else -> {
                    val data = orderData as RecieveOrderYchBean
                    OrderEntity().apply {
                        uuid = data.transId
                        orderNumber = data.orderNumber
                        amount = data.coins
                        money = data.money
                        this.platform = platform
                        payType = PayType.WRITEOFF
                    }
                }
            }

            orderEntity?.let {
                RoomUtil.orderInsert(it)
            }

            orderData
        }catch (e: Exception){
            e.printStackTrace()
            logFile("插入核销订单异常：${e.message}")
            orderData
        }
    }

    override suspend fun insertHttpOrder(
        platform: BackstagePlatform,
        transId: String,
        orderId: String,
        orderNumber: String,
        goodId: String,
        coins: String,
        money: String,
    ) {
        try {
            RoomUtil.orderInsert(OrderEntity().apply {
                uuid = transId
                payUuid = orderId
                this.orderNumber = orderNumber
                amount = coins
                this.money = money
                this.platform = platform
                this.goodId = goodId
            })
            val data = RoomUtil.orderGetByOrderNumber(orderNumber)
            logFile("新增数据 ${GsonUtil.getInstance()?.toJson(data)}")

        }catch (e: Exception){
            e.printStackTrace()

        }
    }

    override suspend fun getOrderSupplement(
        startDate: String,
        endDate: String,
    ): MutableList<SupplementOrderBean> {
        return try {
            val supplementOrderList = mutableListOf<SupplementOrderBean>()
            RoomUtil.orderSupplement(startDate, endDate)?.run {
                logFile("需要补货的订单：${GsonUtil.getInstance()?.toJson(this)}")
                forEach { orderData ->
                    val isSupplementOrder = when (orderData.payType) {
                        PayType.QRCODE -> true
                        PayType.CASH -> true
                        PayType.CARD -> true
                        PayType.WITHDRAWAL -> true
                        PayType.PAIBI -> false
                        PayType.CLEAR -> false
                        PayType.WRITEOFF -> true
                    }
                    if (!isSupplementOrder) return@forEach
                    supplementOrderList.add(
                        SupplementOrderBean(
                            orderData.id,
//                            "${orderData.date.replace("-", "")}${orderData.time.replace(":", "")}",
                            "${orderData.date} ${orderData.time}",
                            orderData.money.ifEmpty { "0" },
                            orderData.amount.ifEmpty { "0" },
                            orderData.amount.ifEmpty { "0" } == orderData.realAmount.ifEmpty { "0" },
                            orderData.realAmount.ifEmpty { "0" }
                        )
                    )
                }
            }
            supplementOrderList
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取出币异常订单异常：${e.message}")
            mutableListOf<SupplementOrderBean>()
        }
    }

    override suspend fun setRealAmount(id: Long, realAmount: String) {
        try {
            RoomUtil.setOrderRealAmount(id, realAmount)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("更新出币异常数据异常：${e.message}")
        }
    }

    override suspend fun verifyOrder(
        platform: BackstagePlatform,
        orderData: Any,
    ): OrderVerifyResult? {
        return try {
            when (platform){
                BackstagePlatform.DEF_MQTT -> OrderVerifyResult(platform, orderData)
                BackstagePlatform.LYY_SDK -> OrderVerifyResult(platform, orderData)
                BackstagePlatform.LYY_BOX -> OrderVerifyResult(platform, orderData)
                BackstagePlatform.WHM_MQTT -> OrderVerifyResult(platform, orderData)
                BackstagePlatform.WHM_MQTT_HEX -> {
                    val data = orderData as RecieveOrderWhmMqttHexBean
                    if (RoomUtil.verifyOrderNumber(platform, data.k) == 0){
                        logFile("订单不存在")
                        OrderVerifyResult(platform, orderData)
                    }else{
                        logFile("订单已存在")
                        null
                    }
                }
                BackstagePlatform.YCH_SDK -> OrderVerifyResult(platform, orderData)
                BackstagePlatform.KKB -> OrderVerifyResult(platform, orderData)
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("更新出币异常数据异常：${e.message}")
            null
        }
    }

    override suspend fun createOneCoinOrder(coins: Long): RepCashDataBean? {
        return try {

            //刷新纸钞套餐数据
            val channelDenominations = CommonUtil.getChannelMode(country).split(";")[0].split(",")
//            val cashConfig = cashConfigHex
//            val channelCoins: MutableList<String> = mutableListOf()
//            for (i in cashConfig.indices step 4){
//                val coins = "${cashConfig.substring(i + 2, i + 4)}${cashConfig.substring(i, i + 2)}".toLong(16)
//                channelCoins.add(coins.toString())
//            }

            val dMoney = channelDenominations[0].toLong()
            val dCoins = "${cashConfigHex.substring(2, 4)}${cashConfigHex.substring(0, 2)}".toLong(16)
            val moneyListStr = "$dMoney,$coins;"

            val totalCoins = dCoins * coins
            val totalMoney = dMoney * coins

            val uuid = CommonUtil.getUuid()
            val order = OrderEntity().apply {
                this.uuid = uuid
                amount = totalCoins.toString()
                money = totalMoney.toString()
                moneyList = moneyListStr
                platform = p
                goodType = PackageType.CASH
                payType = PayType.CASH
                isPay = PayState.SUCCESS
            }

            RoomUtil.orderInsert(order)

            when (p) {
                BackstagePlatform.DEF_MQTT -> {
                    null
                }
                BackstagePlatform.LYY_SDK -> {
                    RepCashDataBean(
                        p,
                        RecieveOrderLyySdkBean(totalMoney.toString(), totalCoins.toString(), uuid, uuid, true),
                        RepCashLyysdk("", "", totalMoney.toString(), totalCoins.toString()),
                        uuid
                    )
                }

                BackstagePlatform.LYY_BOX -> null
                BackstagePlatform.WHM_MQTT -> null
                BackstagePlatform.WHM_MQTT_HEX -> {
                    val payType = 2//硬币
                    val orderUnit = 1//个
//                    val currencyUnit = 4//元
                    val currencyUnit = CommonUtil.getCurrencyUnit(country)
                    val cashDataList: MutableList<CashDataWhmhex> = mutableListOf()
                    val moneyItems = moneyListStr.split(";")
                    moneyItems.forEach { item ->
                        if (item.isNotEmpty()) {
                            val moneyDatas = item.split(",")
                            val itemMoney = moneyDatas[0].toLong()/Config.CONVERSION_RATIO
                            val sum = moneyDatas[1]
                            cashDataList.add(CashDataWhmhex(
                                2,//1-纸钞 2-硬币
                                1,//货币单位 个
                                itemMoney.toLong(),//面额
                                sum.toLong(),//数量
                                1,//编号
                                1//重试次数
                            ))
                        }
                    }
                    logFile("硬币订单上报数据：${GsonUtil.getInstance()?.toJson(order)}")
                    RepCashDataBean(
                        p,
                        RecieveOrderWhmMqttHexBean(totalMoney.toString(), totalCoins.toString(), uuid, uuid, true, payType, orderUnit, "0", currencyUnit),
                        RepCashWhmhex(cashDataList),
                        uuid
                    )
                }

                BackstagePlatform.YCH_SDK -> {
                    RepCashDataBean(
                        p,
                        RecieveOrderYchBean(uuid, dMoney.toString(), dCoins.toString(), uuid, uuid, true, false),
                        RepCashYch(uuid, 0, (dMoney/100).toString(), -1, 0, dCoins, "", System.currentTimeMillis(), 0, ""),
                        uuid
                    )
                }

                BackstagePlatform.KKB -> {
                    RepCashDataBean(
                        p,
                        RecieveOrderKkbBean(uuid, dMoney.toString(), dCoins.toString(), uuid, uuid, true, false),
                        RepCashKkb(uuid, 0, dMoney.toString(), -1, 0, dCoins, "", System.currentTimeMillis(), 0, ""),
                        uuid)
                }
            }
        }catch (e: Exception){
            e.printStackTrace()
            logFile("创建投币订单异常：${e.message}")
            null
        }
    }

    override suspend fun uploadLog(logType: Int, logNumber: String) {
        try {
            if (isUploading) {
                logFile("有日志文件正在上传，不处理本次上传事件")
                return
            }
            val diskPath = Environment.getExternalStorageDirectory().absolutePath
            val folder = diskPath + File.separatorChar + "logger"
            val nowDate = DateTimeUtil.nowDate2

            val dates = if (logType == BuildConfig.LOG_DAY){
                mutableListOf(DateTimeUtil.nowDate2)
            }else if (logType == BuildConfig.LOG_ALL){
                val ds = mutableListOf<String>()
                for (i in 0..6){
                    ds.add(DateTimeUtil.getDatesPass(i))
                }
                ds
            } else {
                mutableListOf(DateTimeUtil.nowDate2)
            }

            val zipFilePath = FileUtil.prepareLogFiles(folder, dates, devNumber)
            logFile("日志压缩文件：$zipFilePath")
            var uploadResult = 2
            zipFilePath?.let {
                val zipFile = File(zipFilePath)

                logFile("压缩文件：${zipFile.absolutePath}")

                uploadResult = 0
                HttpUtil.uploadFile(zipFile, devNumber, object : UploadLogCallback() {
                    override fun fail(call: Call?, e: IOException?) {
                        logFile("上传日志文件失败：${e?.message}")
                        uploadResult = 2
                    }

                    override fun response(call: Call?, response: Response?) {
                        logFile("上传日志文件成功：${response?.message}")
                        uploadResult = 1
                    }
                })

                do {
                    delay(1000)
                }while (uploadResult == 0)

            }?: 2
            delay(2000)
            isUploading = false
            uploadResult
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            logFile("上传日志文件异常：" + e.message)
            isUploading = false
        }
    }

    override suspend fun verifyQrCode(code: String): Boolean {
        return try {
            if (code.isEmpty()){
                return false
            }
            if (!code.contains(".")){
                return false
            }
            val codeArr = code.split(".")
            if (codeArr.size != 3){
                return false
            }
            codeArr[0] == "Q" && codeArr[2] == "A"
        }catch (e: Exception){
            e.printStackTrace()
            false
        }
    }

    /**
     * 检验允许接收面额
     * @param check
     */
    private fun checkAllowDenomination(check: Long): Boolean {
        return try {
            if (channelParams.isEmpty()){
                return false
            }
            if (!channelParams.contains(",")){
                return false
            }

            val denominations: MutableList<Long> = mutableListOf()
            channelParams.split(";")[0].split(",").forEach { denominationItem ->
                try {
                    denominations.add(denominationItem.toLong())
                }catch (e: Exception){
                    logFile("选中面额数据 $denominationItem 异常：${e.message}")
                    return@forEach
                }
            }
            logFile("选中面额：$check 纸钞通道面额：${GsonUtil.getInstance()?.toJson(denominations)}")
            if (denominations.isNotEmpty()){
                denominations.forEach { cashDenomination ->
                    if (cashDenomination == check){
                        return true
                    }
                }
            }
            false
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("checkAllowDenomination()异常：" + e.message)
            false
        }
    }

    /**
     * 检测进钞金额可以获得的币数
     */
    private fun checkMoneyGetCoin(tempMoney: Long): Long {
        return try {
            getCashGoods()?.let {
                val packageMoney = LongArray(it.size)
                for (i in packageMoney.indices) {
                    packageMoney[i] = it[i].price.toLong()
                }

                //排序
                var sort = 0L
                for (i in packageMoney.indices) {
                    for (j in 0 until packageMoney.size - 1 - i) {
                        if (packageMoney[j] < packageMoney[j + 1]) {
                            sort = packageMoney[j]
                            packageMoney[j] = packageMoney[j + 1]
                            packageMoney[j + 1] = sort
                        }
                    }
                }
                calculateOutCoin(it, tempMoney, packageMoney)
            }?:0L
        }catch (e: Exception){
            e.printStackTrace()
            logFile("校验纸钞总额可以获取的币数异常：${e.message}")
            0L
        }
    }

    private fun getCashGoods(): MutableList<CashGoodBean>? {
        return try {
            //刷新纸钞套餐数据
            val cashPackage: String = SPHelper.getCashPackage()
            logFile("纸钞套餐2：$cashPackage")
            var cashGoodBeanList: MutableList<CashGoodBean> = mutableListOf()
            if (cashPackage.isNotEmpty()) {
                cashGoodBeanList = GsonUtil.getInstance()!!
                    .fromJson(cashPackage, object : TypeToken<MutableList<CashGoodBean>>() {}.type)
            } else {
                val bean0 = CashGoodBean("5", "100", "1", "0", 5)
                val bean1 = CashGoodBean("4", "500", "5", "0", 4)
                val bean2 = CashGoodBean("3", "1000", "10", "0", 3)
                val bean3 = CashGoodBean("2", "2000", "20", "0", 2)
                val bean4 = CashGoodBean("1", "5000", "60", "0", 1)
                val bean5 = CashGoodBean("0", "10000", "140", "0", 0)
                cashGoodBeanList.add(bean5)
                cashGoodBeanList.add(bean4)
                cashGoodBeanList.add(bean3)
                cashGoodBeanList.add(bean2)
                cashGoodBeanList.add(bean1)
                cashGoodBeanList.add(bean0)
            }
            cashGoodBeanList
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取纸钞套餐异常2：${e.message}")
            null
        }
    }

    /**
     * 计算需要出币数量
     */
    private fun calculateOutCoin(cashGoodBeanList: MutableList<CashGoodBean>, m: Long, packages: LongArray): Long {
        return try {
            var money = m
            var count = 0L
            for (i in packages.indices) {
                if (money >= packages[i]) {
                    var target: CashGoodBean? = null
                    for (bean in cashGoodBeanList) {
                        if (bean.price.toLong() == packages[i]) {
                            target = bean
                            count = target.value
                                .toLong() + target.flag
                                .toLong()
                            val remain = money - target.price.toLong()
                            count += calculateOutCoin(cashGoodBeanList, remain, packages)
                            return count
//                            return calculateOutCoin(cashGoodBeanList, remain, packages).let { count += it; count }
                        }
                    }
                }
                if (i == packages.size - 1) {
                    if (money < 100) {
                        money = 0
                    }
//                    deviceRemainCashTemp = money
                }
            }
            count
        } catch (e: NumberFormatException) {
            e.printStackTrace()
            logFile("calculateOutCoin()异常：" + e.message)
            0L
        }
    }

    /**
     * 记录进钞面额
     * @param checkMoney 当前进钞面额
     */
    private fun markMoney(checkMoney: Long) {
        try {
            var index = -1
            when (checkMoney) {
                100L -> index = 0
                5 * 100L -> index = 1
                10 * 100L -> index = 2
                20 * 100L -> index = 3
                50 * 100L -> index = 4
                100 * 100L -> index = 5
                else -> {}
            }
            markMoneyArr[index] = markMoneyArr[index] + 1
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("记录纸钞面额异常：" + e.message)
        }
    }

    private fun createCashOrder(
        platform: BackstagePlatform,
        uuid: String,
        money: String,
        coins: String,
        moneyList: String
    ): RepCashDataBean? {
        return try {

            when (platform) {
                BackstagePlatform.DEF_MQTT -> {
                    null
                }
                BackstagePlatform.LYY_SDK -> {
                    RepCashDataBean(
                        platform,
                        RecieveOrderLyySdkBean(money, coins, uuid, uuid, true),
                        RepCashLyysdk("", "", money, coins),
                        uuid
                    )
                }

                BackstagePlatform.LYY_BOX -> null
                BackstagePlatform.WHM_MQTT -> null
                BackstagePlatform.WHM_MQTT_HEX -> {
                    val payType = 1//纸钞
                    val orderUnit = 1//个
//                    val currencyUnit = 4//元
                    val currencyUnit = CommonUtil.getCurrencyUnit(country)
                    val cashDataList: MutableList<CashDataWhmhex> = mutableListOf()
                    val moneyItems = moneyList.split(";")
                    moneyItems.forEach { item ->
                        if (item.isNotEmpty()) {
                            val moneyDatas = item.split(",")
                            val itemMoney = moneyDatas[0].toLong()/Config.CONVERSION_RATIO
                            val sum = moneyDatas[1]
                            cashDataList.add(
                                CashDataWhmhex(
                                1,//1-纸钞 2-硬币
                                    currencyUnit,//货币单位
                                itemMoney.toLong(),//面额
                                sum.toLong(),//数量
                                1,//编号
                                1//重试次数
                            )
                            )
                        }
                    }
                    logFile("纸钞订单上报数据2：${GsonUtil.getInstance()?.toJson(cashDataList)}")
                    RepCashDataBean(
                        platform,
                        RecieveOrderWhmMqttHexBean(money, coins, uuid, uuid, true, payType, orderUnit, "0", currencyUnit),
                        RepCashWhmhex(cashDataList),
                        uuid
                    )
                }

                BackstagePlatform.YCH_SDK -> {
                    null
                }

                BackstagePlatform.KKB -> {
                    null
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("创建现金订单异常：${e.message}")
            null
        }
    }
}